############################################
# 		MCU_interface.py
# 	
# 	Written using PyDev for Python 2.7
#
#
#
#
#
#
############################################

import sys
import serial
import optparse
import time
from time import sleep
# import datetime
import fastCRC




# crc = 0x0000;
# print(fastCRC.stringcrc16('hello world!'))

####################################
# Putsring function for serial write
def puts(s):
	for c in list(str(s)):
		ser.write(c)
####################################


####################################
serialParam = optparse.OptionParser()

serialParam.add_option("-p", "--port",
					action="store",
					type="string",
					dest="port",
					help="port: ttyACM0 (/dev/ttyACM0",
					metavar=" PORT")

serialParam.add_option("-r", "--rate",
					action="store",
					type="int",
					dest="rate",
					help="bitrate in bps (57600)",
					metavar=" RATE")

serialParam.add_option("-t", "--timeout",
					action="store",
					type="int",
					dest="timeout",
					help="time in seconds",
					metavar=" TIMEOUT")

serialParam.add_option("-d", "--bytesize",
					action="store",
					type="int",
					dest="bytesize",
					help="serEIGHT",
					metavar=" DATABITS")

serialParam.add_option("-f", "--file",
					action="store",
					type="string",
					dest="logfile",
					help="logfile filename",
					metavar=" FILE")



serialParam.set_defaults(port="/dev/ttyACM0",
						rate=57600,
						timeout=10,
						bytesize=8,
						logfile="NULL",
						VERBOSE=0)
####################################



####################################
if __name__ == '__main__':
	

# 	ser = serial.Serial(port=serialParam.port, baudrate=serialParam.rate,
# 					 timeout=serialParam.timeout, databits=serialParam.databits)
	
	opt, args = serialParam.parse_args()

	print "port:\t", opt.port
	print "rate:\t", opt.rate
	print "databits:\t", opt.bytesize
	print "timeout:\t", opt.timeout
	
	commandinput = raw_input("\n\nThese are the current settings. Continue? (y/n)")
	if commandinput == "n" or commandinput == "N":
		print "quitting"
		sys.exit()
	else:
		print "opening file and configuring serial port..."
		if opt.logfile != "NULL":
			f = open(serialParam.logfile, "w+")
	try:
		opt.bytesize = serial.EIGHTBITS
		ser = serial.Serial(port=opt.port, baudrate=opt.rate, timeout=opt.timeout)
		if ser.isOpen():
			print "\n\nport opened. sending 'r' for echo test"
			ser.flushInput()
			ser.flushOutput()
			sleep(0.5)  # #necesary for arduino board unless "auto-reboot on new serial session" is bypassed
			ser.write('r')
			print '\ncommand sent. waiting for response'
# 			sleep(1)
			inText = ser.read(1)
			print "response ='%s'" % inText
			if (inText == 'r'):
				print "Target echoed '%s'. Success" % inText
			else:
				print "target echoed '%s'. Check MCU code/settings?" % inText

	
	except serial.SerialException:
# 		print "failed to open the serial port%s: " % (ser.name)
	 print "failed to open serial port\exiting"
	sys.exit(0)
		
# 		serial.serial_time()
			
		
		



####################################


# print(calcString('hello world!', crc))


# print(calcString('hello world!', crc))



# def selectMode(s):
# 	if s=='r':
# 		print "Sending Run Command\t"
# 		ser.write('r')
# 		rxChar = ser.read(1)
# 		
#
# def openSerial(p):
# 	ser = serial.Serial()
# 	try:
# 		if ser.isOpen()
# 			
# 		
# 		
